import React from 'react'
import style from './style'
import Input from '../input'
import SelectList from '../selectList'
import IconFont from '../iconFont'
import cx from 'classnames'
import util from '../../util'
import {FieldContainer, FieldBox} from '../form'

export default
class extends React.Component {

  constructor(props) {
    super(props)
    this.state = {
      showList: false,
      value: props.value || ''
    };
  }

	static defaultProps = {
		onChange: () => {},
		onSelect: () => {},
		fetch: () => {},
		clear: () => {},
		list: [],
		excludeList: []
	}

	handleChange(e) {
		const { showList } = this.state
		if (!showList) {
			this.setState({
				showList: true
			})
		}

		const { value='' } = e.target
		if (value.trim().length) {
      util.throttle(() => {
			  this.props.fetch(value)
      }, 300)
		} else {
			this.props.clear()
		}
		this.setState({
			value
		})

		this.props.onChange(value)
	}

  getDataList() {
    const { list } = this.props
    return (!Array.isArray(list)? list[this.state.value]: list) || []
  }

	handleSelect(i) {
    const selected = this.filter(this.getDataList(), this.props.excludeList)[i]
    this.setState({
      showList: false
    })
    if (!selected) return

		this.setState({
			value: selected.fullName
		})

		this.props.onChange(selected.fullName)
		this.props.onSelect(selected, i)
		this.props.clear()

		if(this.props.keep === false) {
			this.setState({
				value: ''
			}, () => {
				this.refs.input.focus()
			})
		}
	}

	handleBlur() {
		this.blurTimeout = setTimeout(() => {
			this.props.clear()
      this.setState({
        showList: false
      })
		}, 150)
	}

	handleFocus() {
		const { value='' } = this.state
		if (value.trim().length) {
			this.props.fetch(value)
		}
	}
	
	focus() {
		this.refs.input.focus()
	}

	// filter exclude list
	filter(source, exclude) {
		return source.filter(item => exclude.every(v => !util.isEqual(v.userId, item.userId)))
	}

  componentWillUnmount() {
    clearTimeout(this.blurTimeout)
  }

  componentWillReceiveProps(props) {
    if (util.isNull(this.props.value) && !util.isNull(props.value)) {
      this.setState({
        value: props.value
      })
    }
  }

  render() {
		const item = this.props.item || (
			({ avatarUrl, fullName, jobTitle }, attrs={}) => (
				<li {...attrs}>
          {
            avatarUrl?
					  <img src={avatarUrl}/>
            : (
              <IconFont value="avatar" size="25"/>
            )
          }
					<span>{ fullName }</span>
					<span>{ jobTitle }</span>
				</li>
      )
		)
    const {
      label,
      name,
      required,
      width,
    } = this.props;
    return (
      <FieldBox
        label={label}
        name={name}
        required={required}
      >
  			<div 
          data-role="input-list"
  				className={cx({
  					[style.root]: true,
  					[this.props.className]: this.props.className
  				})}
  			>
  				<Input 
            autoFocus={this.props.autoFocus}
  					ref="input"
  					label={''}
            width={width}
            placeholder={this.props.placeholder}
  					onFocus={::this.handleFocus}
  					onBlur={::this.handleBlur}
  					onChange={::this.handleChange}
  					value={this.state.value}
  				/>
          <SelectList
  					handleSelect={::this.handleSelect}
  					data={this.filter(this.getDataList(), this.props.excludeList)}
  					show={this.state.showList}
            item={item}
  					className={style.list}
          />
        </div>
      </FieldBox>
    )
  }
}
